﻿// ==============================================================================
// Copyright(C) 2011 NCS Pte Ltd
//
// SYSTEM NAME			: MOH Online Collaboration Portal
// COMPONENT ID			: NCS.OCP.SharePoint.Javascript.Library
// COMPONENT DESC		: OCP javascript library
//
// CREATED DATE/BY	    : 15-06-2011 / Lee Gary
// DEPENDENCIES         : -
//
// REVISION HISTORY     : 2
// DATE/BY  ISSUE#/SR#/CS/PM#/OTHERS    DESCRIPTION OF CHANGE
// 30-06-2011/Lee Gary -/-/-/-/- Cleanup, merging and maintaining of javascript libraries in system (it's all over the place)
// ==============================================================================

//=== added by Luo Jian Chun 25/08/2011
String.prototype.trim = function () {
    return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
//==

var JCY = {
    Utilities: {
        initjQuerySettings: function (staffId) {
            _staffId = staffId;
            $.support.cors = true, //Allow Cross Origin Resource Sharing
            $.ajaxSetup({
                cache: false, //IE8 likes to cache old data, webkit based browsers love virgins
                dataType: "jsonp", //We are only going to use json as exchange format
                contentType: "application/json; charset=utf-8", //utf-8 format for IE7
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("OCPStaffId", staffId); //HttpRequest header sent to WCF for context propagation
                },
                error: function (x, e) {
                    if (x.status == 0) {
                        alert('Unable to connect to Webservice. Please contact administrator.');
                    } else if (x.status == 404) {
                        alert('Requested URL not found.');
                    } else if (x.status == 500) {
                        //alert('Internel Server Error.');
                        alert(x.responseText);
                    } else if (e == 'parsererror') {
                        // alert('Error.\nParsing JSON Request failed.');
                    } else if (e == 'timeout') {
                        alert('Request Time out.');
                    } else {
                        alert('Unknown Error.\n' + x.responseText);
                    }
                }
            });
        },

        //convert json date string to date
        //format is optional, example: 'MM/dd/yyyy hh:mm:ss'
        //format = 'timeago' returns timeago time
        convertJsonDate: function (jsonDate, format) {
            if (jsonDate != '' && jsonDate != null && jsonDate != 'undefined') {
                //format json date
                var normDate = new Date(parseInt(jsonDate.substr(6)));
                //inner function returning norm date with or without a specific format
                return FormatDate(normDate, format);
            } else
                return '';

            //nested function to re-formats normal date, used by convertJsonDate
            function FormatDate(normDate, format) {
                //format date
                if (format == 'undefined' || format == "" || format == null) {
                    return normDate.format("dd dddd MMM yyyy");
                } else {
                    //check for timeago format
                    if (format.toLowerCase() == 'timeago')
                        return $.timeago(normDate);
                    else
                    //return date with specified format
                        return normDate.format(format);
                }
            }
        },

         //display/hide SharePoint 2010 ribbon UI
        showHideRibbonUI: function () {            
            //hide all the "unused" sharepoint controls
            if ($("#zz15_Menu span").text() != "System Account") {
                if (window.location.pathname.toLowerCase().search("mohipedia") != -1 || window.location.pathname.toLowerCase().search("_layouts") != -1) {
                    if (window.location.pathname.toLowerCase().search("mohipedia") != -1)
                    {
                        OCP.MOHipedia.applyMOHipediaCustomSearch();
                        //widen article section
                        $(".col-fluid-2").css('margin-right', '130px');
                        $(".right-wp-zone-col").css('width', '130px');
                        //end widen article section
                        //$("#s4-ribbonrow").show();
                        $("#ctl00_PageStateActionButton").hide();
                        $("#zz3_SiteActionsMenu_t").hide();
                        $(".s4-breadcrumb-anchor").hide();
                        $("#RibbonContainer-TabRowRight").remove();
                        $(".ms-siteactionsmenu").hide();  
                        $("#s4-ribbonrow").hide();
                    }

                    var startpoint = $("#ctl00_DataListApps_ctl01_LinkApps").attr('href').indexOf('ContextId=')+10;
                    var endpoint = $("#ctl00_DataListApps_ctl01_LinkApps").attr('href').indexOf('&');
                    var tempContext = "";
                    if (endpoint != - 1)
	                    tempContext = $("#ctl00_DataListApps_ctl01_LinkApps").attr('href').substring(startpoint, endpoint);
                    else
	                    tempContext = $("#ctl00_DataListApps_ctl01_LinkApps").attr('href').substring(startpoint);
                    if(window.location.href.indexOf("ContextId") == -1) { //cannot find context id
                        if(window.location.href.indexOf("?") == -1) { //cannot find ?
                            window.location.href += "?ContextId=" + tempContext;
                        }
                        else
                        {
                            window.location.href += "&ContextId=" + tempContext;
                        }              
                    }                    

                    //set every hyperlink on mohipedia page to contain context id
                    $("a").each(function (key, value) {
                        if (value.href.substring(0, 4) != "java") {
                            if(value.href.indexOf("ContextId") == -1) { //cannot find context id
                                if(value.href.indexOf("?") == -1) { //cannot find ?
                                    value.href = value.href + "?ContextId=" + $.queryString("ContextId");
                                } 
                                else 
                                {
                                    value.href = value.href + "&ContextId=" + $.queryString("ContextId");
                                }              
                            }
                        }
                    });

                    //hide "Last modified at <Datetime> by System Account [Edit this page] & Tags
                    if ((window.location.pathname.toLowerCase().search("home.aspx") != -1) || (window.location.pathname.toLowerCase().search("viewmoremohipedia.aspx") != -1 )) {
                        $(".edit-mode-border").width('100%');
                        $(".right-wp-zone-col").hide();
                        $(".col-fluid-2").width('100%');
                        $(".ewiki-margin").hide();
                        $(".edit-mode-border").css('padding', '0 0 0 0');
                        $("#divLike").hide();
                        $(".commentPart").hide();
                        $("#commentContainer").hide();
                        $("#viewMoreComment").hide();
                        $("#MOHipediaTitle").hide();
                    }
                    else {                                                                                                              
                        //loading of form values (summary/sharing option) in edit mode
                        if ($.queryString("ControlMode") == "Edit") {
                            $("#s4-ribbonrow").show();
                            //set article name textbox to readonly
                            //$("#ctl00_ContentPlaceHolder1_PlaceHolderMain_ctl01_PageNameInEditMode_ctl00_onetidIOFile").attr("disabled", true); 
                            //hiding the like and comment webpart
                            $("#divLike").hide();
                            $(".commentPart").hide();
                            $("#commentContainer").hide();
                            $("#viewMoreComment").hide();

                            $("#divSharingOption").hide();
                            $("#option1").parent().hide();
                            $("#option2").parent().hide();
                            $("#option3").parent().hide();
                            var fileName = window.location.pathname.match(/.*\/([^/]+)\.([^?]+)/i)[1];                           
                            OCP.MOHipedia.getMOHipediaByTitle(fileName, function (item) {                                                                                                      
                                $("#ctl00_ContentPlaceHolder1_PlaceHolderMain_ctl01_txtSummary").val(item.Summary);                                    
                                if (item.SharingOption == "within") {
                                    $("#option1").attr("checked", "checked");
                                }
                                else if (item.SharingOption == "all") {
                                    $("#option2").attr("checked", "checked");
                                }
                                else if (item.SharingOption == "allEdit") {
                                    $("#option3").attr("checked", "checked");
                                }
                                if ($.queryString("ContextId") == item.OCPContextId.toString())
                                {
                                    $("#divSharingOption").show();
                                    $("#option1").parent().show();
                                    $("#option2").parent().show();
                                    $("#option3").parent().show();
                                    //display sharing option based on creator context                                                                                                                 
                                        OCP.MOHipedia.getOcpContextWebSiteByContextId($.queryString("ContextId"), function(callback) {                            
                                        $.each(callback, function (index, item){                                
                                            if(item.contextType == "MySite")
                                            {
                                                $("#option1").parent().hide();
                                            }      
                                        });                            
                                    }); 
                                }                                                          
                            });                                                                                                                   
                        }     
                        else
                        {
                            $("#s4-ribbonrow").hide(); 
                            $("#divLike").show();
                            $(".commentPart").show(); 
                            $("#commentContainer").show();
                            $("#viewMoreComment").show();                          
                        }                                             
                    }
                } else {
                    $("#s4-ribbonrow").hide();
                }
            }
        },

        createSharingOptions: function () {
            $('<input type="radio" name="sharingOption" id="sOpt_all" value="all" checked>Share to all</input>').appendTo($("#OCPSharingOption"));
            $('<br/>').appendTo($("#OCPSharingOption"));
            $('<input type="radio" name="sharingOption" id="sOpt_within" value="within">Share within</input>').appendTo($("#OCPSharingOption"));
        },

        getSharingOptionsValue: function () {
            return $("input[@name=OCPsharingOption]:checked").val();
        },

        copyClick: function() {
            clipboardData.setData('text', window.location.href);
        },

        printThisPage: function() {
            window.print();
        }
    },

    AccessFramework: {

        searchStaffInfo: function (staffName, callback) {
            $.ajax({
                type: "GET",
                cache: false, //IE8 likes to cache old data, webkit based browsers love virgins
                dataType: "jsonp", //We are only going to use json as exchange format
                url: AccessFrameworkUrl + "SearchStaffInfo?staffName=" + staffName,
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    var resultJSON = eval('(' + (result) + ')');
                    //var resultJSON = $.parseJSON(result.d);
                    callback(resultJSON);
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }
    }
  }